import { Button, Modal } from "antd";
import { FC, ReactElement, useCallback, useEffect, useState } from "react";
import { Container } from "../TagManage";
import styled from "styled-components";
import Upload from "./Upload";
import { deleteSource, querySource, Source } from "../../../api/source";
import { downloadSourcePath } from "../../../constant/url";
import { useAuth } from "../../../api/AuthContext";
import { Checkbox } from "antd";
import { ROLE } from "../../../api/types";
import { NotificationError } from "../../common/Notification";

interface IProps {}

const SourceManage: FC<IProps> = (): ReactElement => {
  const { auth } = useAuth();
  const [openModal, setOpenModal] = useState(false);
  const [sources, setSources] = useState<Source[]>([]);
  const [updateSource, setUpdateSource] = useState<Partial<Source>>({});
  const [self, setSelf] = useState(false);

  useEffect(() => {
    querySource({ owner: self ? auth._id : "" }).then(({ data }) => {
      console.log(data);
      if (data && data.code === 0) {
        setSources(data.sources);
      }
    });
  }, [auth._id, self]);

  /**
   * 创建完资源
   */
  const handleFile = useCallback(
    (source: Omit<Source, "owner" | "sender">) => {
      setSources(prev => [
        { ...source, owner: auth._id, sender: [auth] } as any,
        ...prev,
      ]);
      setOpenModal(false);
    },
    [auth]
  );

  const deleteItem = (owner: string, _id: string) => () => {
    if (auth.role === ROLE.admin || auth._id === owner) {
      deleteSource({ _id }).then(({ data }) => {
        console.log("删除item", data);
        if (data.code === 0) {
          setSources(prev => prev.filter(item => _id !== item._id));
        }
      });
    } else NotificationError({ message: "权限不足" });
  };

  /**
   * 更新完资源
   */
  const handleUpdate = useCallback(
    ({ _id, ...updateField }: Partial<Source>) => {
      console.log("updateField:", updateField);

      setSources(prev => {
        const sources = [...prev];
        const index = sources.findIndex(item => item._id === _id);
        Object.assign(sources[index], updateField);
        return sources;
      });

      setUpdateSource({});
    },
    []
  );

  return (
    <Container>
      <Main>
        <Head>
          <Button type='primary' onClick={() => setOpenModal(true)}>
            上传资源
          </Button>
          <Checkbox
            checked={self}
            onChange={e => {
              setSelf(e.target.checked);
            }}
          >
            只看自己
          </Checkbox>
        </Head>
        {sources.map(source => (
          <SourceItem key={source._id}>
            <strong>{source.name}</strong>
            <span>{source.description}</span>
            <div>
              <a
                href={`${downloadSourcePath}${source.file}`}
                download={source.file}
                target='_blank'
                rel='noreferrer'
              >
                下载{source.file}
              </a>

              <Button
                type='ghost'
                onClick={deleteItem(source.owner, source._id)}
              >
                删除
              </Button>
              <Button
                type='primary'
                onClick={() => {
                  setUpdateSource(source);
                }}
              >
                更改
              </Button>
            </div>
          </SourceItem>
        ))}
        <Modal
          title={updateSource._id ? "更新资源" : "上传资源"}
          visible={!!updateSource._id || openModal}
          onCancel={() => {
            setOpenModal(false);
            setUpdateSource({});
          }}
          footer={false}
        >
          <Upload
            updateSource={JSON.parse(JSON.stringify(updateSource))}
            handleFile={handleFile}
            handleUpdate={handleUpdate}
          />
        </Modal>
      </Main>
    </Container>
  );
};

export default SourceManage;

const Head = styled.div`
  display: flex;
  align-items: center;
  & > * {
    margin-right: 1rem;
  }
`;

const SourceItem = styled.div`
  margin: 1rem 0;
  background-color: #fffae5;
  padding: 0.5rem;
  box-shadow: 2px 1px 4px #ccc;
  border-radius: 5px;

  & > span {
    color: #666;
    margin-left: 1rem;
  }
  & > div {
    display: flex;
    a {
      flex: 1;
    }
    & > button {
      margin-left: 0.5rem;
    }
  }
`;

const Main = styled.main`
  height: 100%;
  position: relative;
  padding: 1rem;
`;
